/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.socket.server;

import com.socket.server.business_entities.Motor;
import com.socket.server.business_service_components.MotorService;
import com.socket.xml.XMLParser;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;

/**
 *
 * @author CongChinh
 */
public class ServerServiceThread extends Thread {
    private Socket socket;    
    private ServerSide serverSide;
    private PrintWriter printWriter;
    private BufferedReader bufferedReader;
    private String remoteAddress;
    public ServerServiceThread(ServerSide serverSide, Socket sk) {
        super("Service Thread");
        this.serverSide = serverSide;
        socket = sk;
    }
    @Override
    public void run() {        
            try {
                printWriter = new PrintWriter(socket.getOutputStream(), true);
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //get clientSocket's local address
                remoteAddress = bufferedReader.readLine();
                //
                serverSide.setTxaActions(remoteAddress + " connected.");                                
                serverSide.addListClients(remoteAddress);
                //                
                while (true) {
                    if (socket.isClosed() != true) {
                        waiting(); //wait for requests from Client
                    }
                }
            }catch(Exception e) {
                e.printStackTrace();
            }       
    }
    /**
     * wait requests from Client
     * then, process them (xu? ly') :)
     */
    private void waiting() throws Exception {
        //read data request from Client
        String xmlRequest = bufferedReader.readLine();
        
        XMLParser xmlData = new XMLParser();
        xmlData.parserXMLString(xmlRequest);
        String action = xmlData.getValue("action");
        
        if (action.equals("SHOW")) {
            showResponse();
        }
        else if (action.equals("SEARCH")) {
            searchResponse(xmlData);
        }
        else if (action.equals("ADD")) {
            addResponse(xmlData);
        }
        else if (action.equals("UPDATE")) {
            updateResponse(xmlData);
        }
        else if (action.equals("DELETE")) {
            deleteResponse(xmlData);
        }
        else if (action.equals("CLOSE")) {
            closeResponse();
        }       
    }
    /**
     * <XU LY cac request tu Client gui den>
     */
    private void showResponse() {
        XMLParser xml = new XMLParser();
        
        //call business logic layer's service - selectMotors
        MotorService motorService = new MotorService();
        List motors = motorService.selectMotors();
        
        //send data back to Client
        String xmlResponse;        
            xmlResponse  = xml.openTag("response");        
            xmlResponse +=    xml.openTag("data");  
            xmlResponse +=        xml.newItem("size", String.valueOf(motors.size()));                
        for(int j = 0, lsize = motors.size(); j < lsize; j++)
        {
            Motor _motor = (Motor)motors.get(j);
            //send motors info to Client
            xmlResponse +=        xml.openTag("motor");
            xmlResponse +=            xml.newItem("id",_motor.getXeID());
            xmlResponse +=            xml.newItem("name",_motor.getXeName());
            xmlResponse +=            xml.newItem("color",_motor.getXeColor());
            xmlResponse +=            xml.newItem("price",String.valueOf(_motor.getXePrice()));
            xmlResponse +=            xml.newItem("mark",_motor.getxeMark());
            xmlResponse +=            xml.newItem("quantity",String.valueOf(_motor.getXeQuantity()));
            xmlResponse +=        xml.closeTag("motor"); 
        }               
            xmlResponse +=    xml.closeTag("data");
            xmlResponse += xml.closeTag("response");
        //send info to Client
        printWriter.println(xmlResponse);        
    }
    private void searchResponse(XMLParser xmlData) {        
        Motor motor = new Motor();
        String motorID = xmlData.getValue("id");
        
        //call business logic layer's service - selectMotorById(id)
        MotorService motorService = new MotorService();        
        motor = motorService.selectMotorById(motorID);
        
        //send data back to Client
        XMLParser xml = new XMLParser();
        String xmlResponse;        
        if (!motor.getXeID().equals("")) {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=    xml.newItem("status", "ok");
            xmlResponse +=    xml.openTag("data");                
            xmlResponse +=        xml.openTag("motor");
            xmlResponse +=            xml.newItem("id",motor.getXeID());
            xmlResponse +=            xml.newItem("name",motor.getXeName());
            xmlResponse +=            xml.newItem("color",motor.getXeColor());
            xmlResponse +=            xml.newItem("price",String.valueOf(motor.getXePrice()));
            xmlResponse +=            xml.newItem("mark",motor.getxeMark());
            xmlResponse +=            xml.newItem("quantity",String.valueOf(motor.getXeQuantity()));
            xmlResponse +=        xml.closeTag("motor");
            xmlResponse +=    xml.closeTag("data");
            xmlResponse += xml.closeTag("response");            
        } //null
        else {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=    xml.newItem("status", "error");
            xmlResponse +=    xml.newItem("error", "No result.");
            xmlResponse += xml.closeTag("response");            
        }        
        printWriter.println(xmlResponse);
    }
    private void addResponse(XMLParser xmlData) {
        Motor motor = new Motor();
        
        //set value
        motor.setXeID(xmlData.getValue("id"));
        motor.setXeName(xmlData.getValue("name"));
        motor.setxeMark(xmlData.getValue("mark"));
        motor.setXeColor(xmlData.getValue("color"));
        try {
            motor.setXePrice(Double.parseDouble(xmlData.getValue("price")));
        }
        catch(Exception e) {
            motor.setXePrice(0);
        }
        try {
            motor.setXeQuantity(Integer.parseInt(xmlData.getValue("quantity")));
        }
        catch(Exception e) {
            motor.setXeQuantity(0);
        }
        //call business logic layer's service - addMotor
        MotorService motorService = new MotorService();        
        int ok = motorService.addMotor(motor);
        
        //send response back to Client
        String xmlResponse;
        XMLParser xml = new XMLParser();        
        if(ok == 1) {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "ok");
            xmlResponse += xml.closeTag("response");            
        }//0
        else {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "error");
            xmlResponse +=      xml.newItem("error", "Add fail.");
            xmlResponse += xml.closeTag("response");         
        }
        printWriter.println(xmlResponse);
    }
    private void updateResponse(XMLParser xmlData) {        
        Motor motor = new Motor();
        
        //set value
        motor.setXeID(xmlData.getValue("id"));
        motor.setXeName(xmlData.getValue("name"));
        motor.setxeMark(xmlData.getValue("mark"));
        motor.setXeColor(xmlData.getValue("color"));
        try {
            motor.setXePrice(Double.parseDouble(xmlData.getValue("price")));
        }
        catch(Exception e) {
            motor.setXePrice(0);
        }
        try {
            motor.setXeQuantity(Integer.parseInt(xmlData.getValue("quantity")));
        }
        catch(Exception e) {
            motor.setXeQuantity(0);
        }
        //call business logic layer's service - updateMotor
        MotorService motorService = new MotorService();
        int ok = motorService.updateMotor(motor);
        
        //send response back to Client
        String xmlResponse;
        XMLParser xml = new XMLParser();        
        if(ok == 1) {            
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "ok");
            xmlResponse += xml.closeTag("response");            
        }//0
        else {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "error");
            xmlResponse +=      xml.newItem("error", "Update fail.");
            xmlResponse += xml.closeTag("response");            
        }
        printWriter.println(xmlResponse);
    }
    private void deleteResponse(XMLParser xmlData) {
        Motor motor = new Motor();
        //set value
        motor.setXeID(xmlData.getValue("id"));
        
        //call business logic layer's service - deleteMotor
        MotorService motorService = new MotorService();
        int ok = motorService.deleteMotor(motor);
        
        //send response back to Client
        String xmlResponse;
        XMLParser xml = new XMLParser();        
        if(ok == 1) {            
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "ok");
            xmlResponse += xml.closeTag("response");                      
        }//0
        else {
            xmlResponse  = xml.openTag("response");
            xmlResponse +=      xml.newItem("status", "error");
            xmlResponse +=      xml.newItem("error", "Delete fail.");
            xmlResponse += xml.closeTag("response");                        
        }
        printWriter.println(xmlResponse);
    }
    private void closeResponse() throws IOException {
        serverSide.setTxaActions(remoteAddress + " disconnected.");
        serverSide.removeListClients(remoteAddress);
        socket.close();
        printWriter.close();
        bufferedReader.close();
        this.interrupt();
    }  
}
